package com.by.yz.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.by.yz.R;
import com.by.yz.activity.base.BaseActivity;
import com.by.yz.adapter.TopicInfoAdapter;
import com.by.yz.adapter.TopicItemAdapter;
import com.by.yz.common.MFGT;
import com.by.yz.custom.TechnologyTeamDividerItemDecoration;
import com.by.yz.entity.Account;
import com.by.yz.entity.Community;
import com.by.yz.entity.TopicInfo;
import com.by.yz.entity.UserTest;
import com.by.yz.loginUtil.AccountRESTFul;
import com.by.yz.loginUtil.CommunityRESTFul;
import com.by.yz.loginUtil.TopicInfoRESTFul;
import com.by.yz.util.IsNetWork;
import com.by.yz.util.ToJSonObject;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by John on 2016/10/13.
 */
public class HealthTopicActivity extends BaseActivity implements View.OnClickListener{

    private RecyclerView topicListview;
    MaterialRefreshLayout materialRefreshLayout;
    List<TopicInfo> topicList=new ArrayList<TopicInfo>();
    LinearLayout reportTopic;
    TopicInfoAdapter topicInfoAdapter;
    Community community;
    int pag;
    private LinearLayout no_topic;
    List<Community>  communities=new ArrayList<Community>();//社区的分类
    IsNetWork isNetWork;
    Boolean isFresh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e("onCreate","onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.health_topic);
        setToolbarTitle("健康话题");
        topicInfoAdapter=new TopicInfoAdapter(this,topicList);
//        topicList.clear();
//        pag=0;
//        initView();
//        initDatas();
    }


    @Override
    protected void onResume() {
        Log.e("onResume","onResume");
        super.onResume();
    }
    @Override
    protected void onPause() {
        Log.e("onPause","onPause");
        super.onPause();
    }
    @Override
    protected void onStop() {
        Log.e("onStop","onStop");
        super.onStop();
    }
    @Override
    protected void onRestart() {
        Log.e("onRestart","onRestart");
        super.onRestart();
    }
    @Override
    protected void onDestroy() {
        Log.e("onDestroy","onDestroy");
        super.onDestroy();
    }

    private void initDatas() {
        pag=0;
        getCommunity();
        getCommunityTopics();
        initRefresh();
    }

    /*
	获得社区分类
	 */
    public  void getCommunity(){

        CommunityRESTFul communityRESTFul=new CommunityRESTFul();
        communityRESTFul.getcommunities(new CommunityRESTFul.CommunityGETCallBack() {
            @Override
            public void ok(JSONArray response) throws JSONException {
                Log.e("sssss",response.toString());

                for (int i=0;i<response.length();i++){
                    JSONObject jsonObject= response.getJSONObject(i);
                    community= ToJSonObject.jsonToBean(jsonObject.toString(),Community.class);
                    communities.add(i,community);
                }
                topicInfoAdapter.notifyDataSetChanged();
            }

            @Override
            public void error(String response) {
                communities=null;
            }
        });
    }

    /**
     * 获得社区给定的话题
     */
    public void getCommunityTopics() {
        String name="健康话题";
        try {
            String strname=URLEncoder.encode(name, "UTF-8");
            TopicInfoRESTFul topicInfoRESTFul=new TopicInfoRESTFul();
            topicInfoRESTFul.getCommunityTopicInfo1(strname,pag,new TopicInfoRESTFul.MyGetCallBack() {
                @Override
                public void error(String error) {
                    Toast.makeText(HealthTopicActivity.this, "话题已加载完!", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void ok(JSONArray response) throws JSONException {
                    pag++;
                    TopicInfo topicInfos;
                    try {
                        if (response.length() == 0 && isFresh == true) {
                            Toast.makeText(HealthTopicActivity.this, "没有可以刷新的数据", Toast.LENGTH_SHORT).show();
                        } else if (response.length() != 0 && isFresh == true) {
                            Toast.makeText(HealthTopicActivity.this, "刷新" + response.length() + "条数据", Toast.LENGTH_SHORT).show();
                        } else if (response.length() == 0 && isFresh == false) {
                            Toast.makeText(HealthTopicActivity.this, "没有可以加载的数据", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(HealthTopicActivity.this, "加载" + response.length() + "条数据", Toast.LENGTH_SHORT).show();
                        }
                    }catch (Exception e){

                    }
                    if (response.length() == 0 && pag == 1) {
                        no_topic.setVisibility(View.VISIBLE);
                        materialRefreshLayout.setVisibility(View.GONE);
                    } else {
                        no_topic.setVisibility(View.GONE);
                        materialRefreshLayout.setVisibility(View.VISIBLE);
                        for (int i = 0; i < response.length(); i++) {
                            JSONObject jsonObject = response.getJSONObject(i);
                            topicInfos = ToJSonObject.jsonToBean(jsonObject.toString(), TopicInfo.class);
                            if(topicInfos.getComunity()!=null&&topicInfos.getComunity().equals("健康话题")) {
                                topicList.add(topicInfos);
                            }
                        }
                        topicInfoAdapter.notifyDataSetChanged();
                    }
                }
            });
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    }
    public void initRefresh(){
        materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
                android.os.Handler handler=new android.os.Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isFresh=true;
                        materialRefreshLayout.finishRefresh();
                        getCommunityTopics();
                    }
                },1000);

            }

            @Override
            public void onRefreshLoadMore(final MaterialRefreshLayout materialRefreshLayout) {
                android.os.Handler handler=new android.os.Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isFresh=false;
                        getCommunityTopics();
                        /**
                         * 完成加载数据后，调用此方法，要不然刷新的效果不会消失
                         */
                        materialRefreshLayout.finishRefreshLoadMore();
                    }
                }, 1000);
            }
        });
    }
    private void initView() {
        topicListview=(RecyclerView) findViewById(R.id.health_topic);
        topicListview.setLayoutManager(new LinearLayoutManager(topicListview.getContext()));
        topicListview.setAdapter(topicInfoAdapter );
        topicListview.addItemDecoration(new TechnologyTeamDividerItemDecoration(this,TechnologyTeamDividerItemDecoration.VERTICAL_LIST));
        reportTopic=(LinearLayout) findViewById(R.id.report_health_topic_layout);
        reportTopic.setOnClickListener(this);
        materialRefreshLayout = (MaterialRefreshLayout) findViewById(R.id.refresh);
        materialRefreshLayout.setLoadMore(true);
        no_topic = (LinearLayout) findViewById(R.id.no_topic);

        View view=(View)findViewById(R.id.view);

        UserTest userTest;
        userTest = (UserTest) getIntent().getSerializableExtra("healthtopic");
        if(!userTest.getflag()){
            reportTopic.setVisibility(View.GONE);
            view.setVisibility(View.GONE);
        }

    }
    @Override
    protected void onStart() {
        Log.e("onStart","onStart");
        super.onStart();
        if(isNetWork.isNetworkAvailable(this)) {
            topicList.clear();
            pag=0;
            initView();
            initDatas();
        }else {
            //无网络连接情况
            new AlertDialog.Builder(this)
                    .setTitle("提示!")
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setMessage("检测到您还没开启网络，请开启")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("开启",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    startActivity(new Intent(
                                            Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
                                }
                            }).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.report_health_topic_layout:
                Intent intent=new Intent(this,ReportTopicActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("currentCommunity",community);
                intent.putExtras(bundle);
                startActivity(intent);
//                MFGT.startActivity(this, ReportTopicActivity.class);
                break;
        }
    }
}

/*
package com.by.yz.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.by.yz.R;
import com.by.yz.activity.base.BaseActivity;
import com.by.yz.adapter.TopicInfoAdapter;
import com.by.yz.adapter.TopicItemAdapter;
import com.by.yz.common.MFGT;
import com.by.yz.custom.TechnologyTeamDividerItemDecoration;
import com.by.yz.entity.Account;
import com.by.yz.entity.Community;
import com.by.yz.entity.TopicInfo;
import com.by.yz.entity.UserTest;
import com.by.yz.loginUtil.AccountRESTFul;
import com.by.yz.loginUtil.CommunityRESTFul;
import com.by.yz.loginUtil.TopicInfoRESTFul;
import com.by.yz.util.IsNetWork;
import com.by.yz.util.ToJSonObject;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

*/
/**
 * Created by John on 2016/10/13.
 *//*

public class HealthTopicActivity extends BaseActivity implements View.OnClickListener{

    private RecyclerView topicListview;
    MaterialRefreshLayout materialRefreshLayout;
    List<TopicInfo> topicList=new ArrayList<TopicInfo>();
    LinearLayout reportTopic;
    TopicInfoAdapter topicInfoAdapter;
    Community community;
    int pag;
    List<Community>  communities=new ArrayList<Community>();//社区的分类
    IsNetWork isNetWork;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e("onCreate","onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.health_topic);
        setToolbarTitle("健康话题");
        topicInfoAdapter=new TopicInfoAdapter(this,topicList);
//        topicList.clear();
//        pag=0;
//        initView();
//        initDatas();
    }


    @Override
    protected void onResume() {
        Log.e("onResume","onResume");
        super.onResume();
    }
    @Override
    protected void onPause() {
        Log.e("onPause","onPause");
        super.onPause();
    }
    @Override
    protected void onStop() {
        Log.e("onStop","onStop");
        super.onStop();
    }
    @Override
    protected void onRestart() {
        Log.e("onRestart","onRestart");
        super.onRestart();
    }
    @Override
    protected void onDestroy() {
        Log.e("onDestroy","onDestroy");
        super.onDestroy();
    }

    private void initDatas() {
        pag=0;
        getCommunity();
        getCommunityTopics();
        initRefresh();
    }

    */
/*
	获得社区分类
	 *//*

    public  void getCommunity(){

        CommunityRESTFul communityRESTFul=new CommunityRESTFul();
        communityRESTFul.getcommunities(new CommunityRESTFul.CommunityGETCallBack() {
            @Override
            public void ok(JSONArray response) throws JSONException {
                Log.e("sssss",response.toString());

                for (int i=0;i<response.length();i++){
                    JSONObject jsonObject= response.getJSONObject(i);
                    community= ToJSonObject.jsonToBean(jsonObject.toString(),Community.class);
                    communities.add(i,community);
                }
                topicInfoAdapter.notifyDataSetChanged();

            }

            @Override
            public void error(String response) {
                communities=null;
            }
        });
    }

    */
/**
 * 获得社区给定的话题
 *//*

    public void getCommunityTopics() {
        String name="健康话题";
        try {
            String strname=URLEncoder.encode(name, "UTF-8");
            TopicInfoRESTFul topicInfoRESTFul=new TopicInfoRESTFul();
            topicInfoRESTFul.getCommunityTopicInfo1(strname,pag,new TopicInfoRESTFul.MyGetCallBack() {
                @Override
                public void error(String error) {
                    Toast.makeText(HealthTopicActivity.this, "话题已加载完!", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void ok(JSONArray response) throws JSONException {
                    pag++;
                    TopicInfo topicInfos;
                    for (int i = 0; i < response.length(); i++) {
                        JSONObject jsonObject = response.getJSONObject(i);
                        topicInfos = ToJSonObject.jsonToBean(jsonObject.toString(), TopicInfo.class);
                        if(topicInfos.getComunity()!=null&&topicInfos.getComunity().equals("健康话题")) {
                            topicList.add(topicInfos);
                        }
                    }
                    topicInfoAdapter.notifyDataSetChanged();

                }
            });
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    }
    public void initRefresh(){
        materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
                android.os.Handler handler=new android.os.Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        materialRefreshLayout.finishRefresh();
                        getCommunityTopics();
                    }
                },1000);

            }
            public void onfinish(){
                Toast.makeText(HealthTopicActivity.this, "刷新完成", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onRefreshLoadMore(final MaterialRefreshLayout materialRefreshLayout) {
                android.os.Handler handler=new android.os.Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(HealthTopicActivity.this, "加载完成", Toast.LENGTH_SHORT).show();
                        getCommunityTopics();
                        */
/**
 * 完成加载数据后，调用此方法，要不然刷新的效果不会消失
 *//*

                        materialRefreshLayout.finishRefreshLoadMore();
                    }
                }, 1000);
            }
        });
    }
    private void initView() {
        topicListview=(RecyclerView) findViewById(R.id.health_topic);
        topicListview.setLayoutManager(new LinearLayoutManager(topicListview.getContext()));
        topicListview.setAdapter(topicInfoAdapter );
        topicListview.addItemDecoration(new TechnologyTeamDividerItemDecoration(this,TechnologyTeamDividerItemDecoration.VERTICAL_LIST));
        reportTopic=(LinearLayout) findViewById(R.id.report_health_topic_layout);
        reportTopic.setOnClickListener(this);
        materialRefreshLayout = (MaterialRefreshLayout) findViewById(R.id.refresh);
        materialRefreshLayout.setLoadMore(true);

        View view=(View)findViewById(R.id.view);

        UserTest userTest;
        userTest = (UserTest) getIntent().getSerializableExtra("healthtopic");
        if(!userTest.getflag()){
            reportTopic.setVisibility(View.GONE);
            view.setVisibility(View.GONE);
        }

    }
    @Override
    protected void onStart() {
        Log.e("onStart","onStart");
        super.onStart();
        Log.e("ylj","onStart");
        if(isNetWork.isNetworkAvailable(this)) {
            topicList.clear();
            pag=0;
            initView();
            initDatas();
        }else {
            //无网络连接情况
            new AlertDialog.Builder(this)
                    .setTitle("提示!")
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setMessage("检测到您还没开启网络，请开启")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("开启",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    startActivity(new Intent(
                                            Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
                                }
                            }).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.report_health_topic_layout:
                Intent intent=new Intent(this,ReportTopicActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("currentCommunity",community);
                intent.putExtras(bundle);
                startActivity(intent);
//                MFGT.startActivity(this, ReportTopicActivity.class);
                break;
        }
    }
}
*/
